//
//  Router.swift
//  TodayNews
//
//  Created by ZhangBo on 2019/6/17.
//  Copyright © 2019 ZhangBo. All rights reserved.
//

import UIKit

public class RouterUtils {
    //获取当前页面
    public class func currentTopViewController() -> UIViewController? {
        if let rootViewController = UIApplication.shared.keyWindow?.rootViewController {
            return currentTopViewController(rootViewController: rootViewController)
        } else {
            return nil
        }
    }

    public class func currentTopViewController(rootViewController: UIViewController) -> UIViewController {
        if (rootViewController.isKind(of: UITabBarController.self)) {
            let tabBarController = rootViewController as! UITabBarController
            return currentTopViewController(rootViewController: tabBarController.selectedViewController!)
        }
        if (rootViewController.isKind(of: UINavigationController.self)) {
            let navigationController = rootViewController as! UINavigationController
            return currentTopViewController(rootViewController: navigationController.visibleViewController!)
        }
        if ((rootViewController.presentedViewController) != nil) {
            return currentTopViewController(rootViewController: rootViewController.presentedViewController!)
        }
        return rootViewController
    }
}

/// 用于配置各跳转
public protocol RouterPathable {
    var any: AnyClass { get }
    var params: RouterParameter? { get }
}

public typealias RouterParameter = [String: Any]

/// controller需遵守此协议，才可Router
public protocol Routable {
    static func initWithParams(params: RouterParameter?) -> UIViewController?
}


class Router<Path: RouterPathable> {
}

/// for url
extension Router {
    static func openTel(_ phoneNum: String) {
        if let url = URL(string: "tel://\(phoneNum)") {
            UIApplication.shared.open(url)
        }
    }
}

/// for controllers
extension Router {
    static func open(_ path: Path, present: Bool = false, animated: Bool = true, presentComplete: (() -> Void)? = nil) {

        if let cls = path.any as? Routable.Type, let vc = cls.initWithParams(params: path.params) {
            vc.hidesBottomBarWhenPushed = true
            let topViewController = RouterUtils.currentTopViewController()
            if topViewController?.navigationController != nil && !present {
                topViewController?.navigationController?.pushViewController(vc, animated: animated)
            } else {
                topViewController?.present(vc, animated: animated, completion: presentComplete)
            }
        } else {
            d_print("============== \n error router path")
        }
    }
}
